<template>
	<!-- 供应商-供应商列表 -->
	<div>
		<!-- 供应商-供应商列表修改 -->
		<Card :bordered="false" dis-hover class="ivu-mt" :padding="0">
			<Form inline class="formValidate mt20" :label-width="80" @submit.native.prevent>
				<FormItem label="搜索：" label-for="store_name">
					<Input placeholder="请输入公司名称" v-model="formValidate.company" class="input-add" />
					<Input placeholder="请输入手机号" v-model="formValidate.phone" class="input-add" />
					<Input placeholder="请输入主营产品" v-model="formValidate.product" class="input-add" />
					<Select v-model="formValidate.status" filterable class="input-add" placeholder="请选择跟进状态" clearable>
						<Option v-for="item in genjinList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
					<Select v-model="formValidate.admin_id" placeholder="请选择招商员" filterable class="input-add" clearable>
						<Option v-for="item in adminList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
					<div class="input-add ivu-input-wrapper ivu-input-wrapper-default ivu-input-type-text">
						<Cascader :data="addresData" :load-data="loadData" class="input-add"
							v-model="formValidate.addressSelect" @on-change="addchack" change-on-select clearable
							placeholder="请选择国家地区"></Cascader>
					</div>

					<Button type="primary" @click="searchList()">查询</Button>
				</FormItem>
			</Form>
		</Card>

		<Card :bordered="false" dis-hover class="ivu-mt">
			<!-- 操作 -->
			<Button type="primary" class="btn" @click="addSupplier">添加客户资料</Button>
			<!-- 表格 -->
			<Table :columns="columns" :data="tabList" ref="table" highlight-row no-data-text="暂无数据"
				no-filtered-data-text="暂无筛选结果" class="orderData ivu-mt" max-height="600">
				<!-- 状态 -->
				<template slot-scope="{ row, index }" slot="is_show">
					<i-switch v-model="row.is_show" @on-change="onchangeIsShow(row)" :true-value="1" :false-value="0"
						size="large">
						<span slot="open">开启</span>
						<span slot="close">关闭</span>
					</i-switch>
				</template>

				<!-- 操作 -->
				<template slot-scope="{ row, index }" slot="action">
					<a @click="showZhaoShangDetail(row)" v-auth="['admin-supplier-allocation-merchants']">分配招商员</a>
					<Divider type="vertical" />
					<a @click="kaihu(row)">一键开户</a>
					<Divider type="vertical" />
					<a @click="edit(row)">编辑</a>
					<Divider type="vertical" />
					<a type="primary" @click="showFollowUpDetail(row)">查看跟进</a>
					<!-- <Divider type="vertical" />
					<a @click="del(row, '删除客户资料', index)" class="del">删除</a> -->
				</template>
				<!-- no-data-text="暂无数据" highlight-row -->
				<!-- no-filtered-data-text="暂无筛选结果" -->
			</Table>
			<div>
				<!-- 分页 -->
				<div class="acea-row row-right page">
					<Page :total="page.total" :current="page.pageNum" show-elevator show-total @on-change="pageChange"
						:page-size="page.pageSize" @on-page-size-change="limitChange" />
				</div>
			</div>
		</Card>
		<menus-from :formValidate="formValidate" ref="menusFrom"></menus-from>

		<Modal v-model="followUpModalVisible" title="跟进信息" :footer-hide="true" width="800">
			<div class="article-manager video-icon form-submit" id="shopp-manager">
				<Card :bordered="false" dis-hover class="ivu-mt">
					<Form class="formValidate" ref="formValidate" :model="formData"
						:label-width="width" :label-position="labelPosition" @submit.native.prevent>
						<Col span="24">
						<FormItem label="跟进人：" prop="supplier_name">
							<Input v-model="formData.supplier_name" :disabled="true" v-width="460" />
						</FormItem>
						</Col>

						<Col span="24">
						<FormItem label="跟进状态：" prop="status">
							<Select v-model="formData.status" v-width="460">
								<Option :value="1">合作</Option>
								<Option :value="2">签约中</Option>
								<Option :value="3">有意向</Option>
								<Option :value="4">无意向</Option>
							</Select>
						</FormItem>
						</Col>
						<Col span="24">
						<FormItem label="跟进信息：" prop="follow_up_info">
							<div v-for="(item, index) in formData.follow_up_info" :key="index"
								style="margin-bottom: 8px;margin-left: 70px;">
								<div class="follow-header">
									<span class="follow-time-label">跟进时间：</span>
									<span class="follow-time-value">
										{{ formatTime(item.time)  || '保存后自动生成' }}
									</span>
								</div>

								<div style="display: flex;">
									<Input type="textarea" v-model="item.content" placeholder="请输入跟进信息"
										:autosize="{ minRows: 2, maxRows: 4 }" class="follow-content" />
									<Button type="error" icon="md-remove" @click="removeFollowUp(index)"
										style="margin-left: 8px;" v-if="formData.follow_up_info.length > 1" />
								</div>

							</div>
							<Button type="dashed" icon="md-add" @click="addFollowUp"
								style="margin-left: 70px;">添加跟进信息</Button>
						</FormItem>
						</Col>
					</Form>
				</Card>
				<Card :bordered="false" dis-hover>
					<Form>
						<FormItem>
							<div class="floatRight">
								<Button type="primary" class="submission" @click="handleCancel()">取消</Button>
								<div style="display: inline-block;width: 15px;"></div>
								<Button type="primary" class="submission"
									@click="handleSubmit('formValidate')">保存</Button>
							</div>
						</FormItem>
					</Form>
				</Card>
			</div>
		</Modal>
		<Modal v-model="zhaoShangModalVisible" title="招商员列表" :footer-hide="true" width="800">
			<Table ref="followUpTable" :columns="followUpColumns" :data="followUpDataZs"
				@on-current-change="handleRowSelect" highlight-row></Table>

			<!-- 分页 -->
			<div class="acea-row row-right page">
				<Page :total="page1.total" :current="page1.pageNum" show-elevator show-total :page-size="page1.pageSize"
					@on-change="pageChange1" @on-page-size-change="limitChange" />
			</div>

			<!-- 底部按钮 -->
			<div class="modal-footer" style="text-align: right; margin-top: 20px;">
				<Button type="default" @click="zhaoShangModalVisible = false">取消</Button>
				<Button type="primary" @click="submitFollowUp">确认</Button>
			</div>
		</Modal>
	</div>
</template>
<script>
	import {
		mapState
	} from 'vuex'
	import util from '@/libs/util'
	import Setting from '@/setting'
	import {
		customerInformationListApi,
		putSupplierStatus,
		supplierLogin,
		getCustomerInformation,
		createCustomerInformationApi,
		createCustomerInformationFollowApi,
		getAdminListApi,
		getDefaultZhaoShangIdApi,
		getSystemAdminZhaoShangList,
		setZhaoShangDataApi
	} from '@/api/supplier'
	import Template from '../../setting/devise/template.vue'
	import menusFrom from "./components/menusFrom";
	import {
		areaInfoApi
	} from '@/api/store'
	export default {
		name: '',
		components: {
			menusFrom,
			Template
		},
		props: {},
		data() {
			return {
				followUpColumns: [{
						title: 'ID',
						key: 'id',
						width: 80
					},
					{
						title: '姓名',
						key: 'real_name'
					},
					{
						title: '手机号',
						key: 'phone'
					}
				],
				formFollowData: {
					selected_follow_up: 0,
					supplier_id: 0,
				},
				selectedFollowUp: null,
				followUpDataZs: [],
				addresData: [],
				adminList: [],
				genjinList: [{
					value: 0,
					label: "未跟进"
				}, {
					value: 1,
					label: "合作"
				}, {
					value: 2,
					label: "签约中",
				}, {
					value: 3,
					label: "有意向",
				}, {
					value: 4,
					label: "无意向"
				}],
				followUpModalVisible: false,
				zhaoShangModalVisible: false,
				followUpData: {}, // 传入的整条数据
				roterPre: Setting.roterPre,
				keywords: '',
				BaseURL: '',
				page1: {
					total: 0, // 总条数
					pageNum: 1, // 当前页
					pageSize: 15, // 每页显示条数
				},
				formData: {
					id: 0,
					supplier_name: '',
					follow_up_time: '',
					status: '',
					follow_up_info: [{
							content: '',
							time: ''
						} // 修改为对象数组，包含内容和时间
					],
				},
				formValidate: {
					admin_id: 0,
					product: "",
					status: -1,
					extract_type: '',
					address: "",
					type: 1,
					phone: "",
					company: "",
					nireid: '',
					data: 'thirtyday',
					page: 1,
					limit: 20,
					province: 0,
					city: 0,
					area: 0,
					street: 0,
				},
				loading: false,
				page: {
					total: 0, // 总条数
					pageNum: 1, // 当前页
					pageSize: 15, // 每页显示条数
				},
				columns: [{
						title: 'ID',
						key: 'id',
						minWidth: 80,
					},
					{
						title: '招商员',
						minWidth: 80,
						key: 'real_name',
					},
					{
						title: '公司名称',
						key: 'company_name',
						minWidth: 100,
					},
					{
						title: '公司名称(英)',
						key: 'company_name_en',
						minWidth: 100,
					},
					{
						title: '联系人',
						key: 'contacts',
						minWidth: 80,
					},
					{
						title: '联系人电话',
						key: 'phone',
						minWidth: 100,
					},
					{
						title: '联系人邮箱',
						key: 'email',
						minWidth: 100,
					},
					{
						title: '国家地区',
						key: 'address',
						minWidth: 100,
					},
					{
						title: '主营产品',
						key: 'product',
						minWidth: 100,
					},
					{
						title: '微信群ID',
						key: 'wx',
						minWidth: 100,
					},
					{
						title: '跟进状态',
						key: 'status_name',
						minWidth: 100,
					},
					{
						title: '下次移入公海时间',
						key: 'open_sea_day_name',
						minWidth: 100,
					},
					{
						title: '操作',
						slot: 'action',
						minWidth: 140,
					},
				],
				tabList: [],
			}
		},
		computed: {
			...mapState('admin/layout', ['isMobile']),
			labelWidth() {
				return this.isMobile ? undefined : 80
			},
			labelPosition() {
				return this.isMobile ? 'top' : 'right'
			},
		},
		watch: {},
		created() {
			let data = {
				pid: 0,
				id: 1
			}
			this.cityInfo(data)
			this.getSupplier()
			this.getAdminList()
		},
		mounted() {},
		methods: {
			pageChange1(index) {
				this.page1.pageNum = index
				this.findZhaoShangRecord();
			},
			handleRowSelect(currentRow) {
				this.selectedFollowUp = currentRow.id;
				this.formFollowData.selected_follow_up = currentRow.id
			},
			// 提交
			submitFollowUp() {
				if (!this.selectedFollowUp) {
					this.$Message.warning('请选择一名招商员');
					return;
				}
				// 提交逻辑
				console.log('选择的招商员：', this.selectedFollowUp);

				// 提交后关闭弹窗
				this.zhaoShangModalVisible = false;
				console.log("---------", this.formFollowData)
				if (this.formFollowData.selected_follow_up && this.formFollowData.supplier_id) {
					setZhaoShangDataApi(this.formFollowData)
						.then(async (res) => {
							this.$Message.success("保存成功")
							this.$router.push({
								path: this.roterPre + '/supplier/customer-information/list'
							})
							this.getSupplier()
						})
						.catch((res) => {
							this.$Message.error(res.msg)
						})
				}
			},
			showZhaoShangDetail(row) {
				this.zhaoShangModalVisible = true;
				this.formFollowData.supplier_id = row.id;
				this.getDefaultFollowId(row);
			},
			getDefaultFollowId(row) {
				getDefaultZhaoShangIdApi(row.id)
					.then((res) => {
						this.defaultFollowUpId = res.data.id;
						this.findZhaoShangRecord(); // 拿到列表后再处理选中逻辑
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			findZhaoShangRecord() {
				let data = {
					keywords: this.keywords1,
					page: this.page1.pageNum,
					limit: this.page1.pageSize,
				};
				getSystemAdminZhaoShangList(data)
					.then((res) => {
						this.followUpDataZs = res.data.list;
						this.page1.total = res.data.count;
						this.followUpDataZs = res.data.list.map(item => {
							return {
								...item,
								_highlight: item.id === this.defaultFollowUpId, // ⭐ 默认选中项
							};
						});

					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			// 获取省市区
			cityInfo(data) {
				areaInfoApi(data).then((res) => {
					this.addresData = res.data
				})
			},
			loadData(item, callback) {
				item.loading = true
				areaInfoApi({
					pid: item.value
				}).then((res) => {
					item.children = res.data
					item.loading = false
					callback()
				})
			},
			// 选择省市区
			addchack(e, selectedData) {
				if (!e || e.length === 0) {
					this.formValidate.province = 0;
					this.formValidate.city = 0;
					this.formValidate.area = 0;
					this.formValidate.street = 0;
				} else {
					e.forEach((i, index) => {
						if (index == 0) {
							this.formValidate.province = i
						} else if (index == 1) {
							this.formValidate.city = i
						} else if (index == 2) {
							this.formValidate.area = i
						} else {
							this.formValidate.street = i
						}
					})
					let addressInfo = [];
					selectedData.forEach(item => {
						addressInfo.push(item.label)
					})
					this.formValidate.address = addressInfo.join('');
				}

			},
			handleCancel() {
				this.formData = {
					id: 0,
					supplier_name: '',
					status: '',
					follow_up_info: [{
						content: '',
						time: ''
					}], // 重置为对象数组
				}
				this.followUpModalVisible = false;
			},
			formatTime(val) {
				if (!val) return '保存后自动生成'
				const d = new Date(val)
				const year = d.getFullYear()
				const month = ('0' + (d.getMonth() + 1)).slice(-2)
				const day = ('0' + d.getDate()).slice(-2)
				const hour = ('0' + d.getHours()).slice(-2)
				const minute = ('0' + d.getMinutes()).slice(-2)
				return `${year}-${month}-${day} ${hour}:${minute}`
			},
			addFollowUp() {
				this.formData.follow_up_info.push({
					content: '',
					time: ''
				});
			},
			removeFollowUp(index) {
				this.formData.follow_up_info.splice(index, 1);
			},
			getAdminList() {
				getAdminListApi()
					.then(async (res) => {
						this.adminList = res.data.list
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},
			handleSubmit() {
				this.followUpModalVisible = false;
				if (this.formData.id) {
					createCustomerInformationFollowApi(this.formData.id, this.formData)
						.then(async (res) => {
							this.$Message.success("保存成功")
							this.$router.push({
								path: this.roterPre + '/supplier/customer-information/list'
							})
							this.getSupplier()
						})
						.catch((res) => {
							this.$Message.error(res.msg)
						})
				}
			},
			// 弹窗触发
			showFollowUpDetail(row) {
				this.followUpData = row;
				this.followUpModalVisible = true;
				this.findRecord(row);
			},
			findRecord(row) {
				getCustomerInformation(row.id)
					.then(async (res) => {
						this.formData = res.data.info
						let info = res.data.info
						this.formData = info
						if (info.follow_up_info == null) {
							this.formData.follow_up_info = []
						}
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},
			// 时间格式化函数
			formatFollowUpTime(time) {
				if (!time) return '无';
				const date = new Date(time);
				const y = date.getFullYear();
				const m = ('0' + (date.getMonth() + 1)).slice(-2);
				const d = ('0' + date.getDate()).slice(-2);
				const h = ('0' + date.getHours()).slice(-2);
				const i = ('0' + date.getMinutes()).slice(-2);
				return `${y}-${m}-${d} ${h}:${i}`;
			},

			// 根据 follow_up_person id 获取人名（你可以替换为接口映射）
			getFollowUpPersonName(id) {
				const map = {
					1: '张三',
					2: '李四',
					0: '系统自动' // 示例用
				};
				return map[id] || '未知';
			},
			// 编辑展位
			editWarehouseExhibition(row) {
				this.$refs.menusFrom.modals = true;
				this.$refs.menusFrom.titleFrom = "编辑展位";
				this.formValidate = row;
			},
			kaihu(row) {
				this.$router.push({
					path: this.roterPre + '/supplier/supplierAdd/' + row.id,
					query: {
						type: 1
					}
				})
			},
			addSupplier() {
				this.$router.push({
					path: this.roterPre + '/supplier/customerInformationAdd'
				})
			},
			getSupplierAgreement(row) {
				this.$router.push({
					path: this.roterPre + '/supplier/supplierAgreement/List/' + row.id
				})
			},

			pageChange(index) {
				this.page.pageNum = index
				this.getSupplier()
			},

			limitChange(limit) {
				this.page.pageSize = limit
				this.getSupplier()
			},
			searchList() {
				this.page.pageNum = 1;
				this.page.pageSize = 15;
				this.getSupplier();
			},
			// 获取供应商列表
			getSupplier() {
				if (this.formValidate.status == undefined) {
					this.formValidate.status = -1
				}
				let data = {
					company_name: this.formValidate.company,
					phone: this.formValidate.phone,
					type: this.formValidate.type,
					admin_id: this.formValidate.admin_id,
					province: this.formValidate.province,
					city: this.formValidate.city,
					area: this.formValidate.area,
					status: this.formValidate.status,
					product: this.formValidate.product,
					page: this.page.pageNum, // 当前页
					limit: this.page.pageSize, // 每页显示条数

				}
				customerInformationListApi(data)
					.then(async (res) => {
						this.tabList = res.data.list
						this.page.total = res.data.count
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},

			// 编辑
			edit(row) {
				this.$router.push({
					path: this.roterPre + '/supplier/customerInformationAdd/' + row.id
				})
			},

			// 修改状态
			onchangeIsShow(row) {
				putSupplierStatus(row.id, row.is_show)
					.then(async (res) => {
						this.$Message.success(res.msg)
					})
					.catch((res) => {
						this.$$Message.error(res.msg)
					})
			},

			// 进入供应商
			goSupplier(row) {
				supplierLogin(row.id)
					.then(async (res) => {
						let data = res.data
						let expires = data.expires_time
						util.cookies.setSupplier('token', data.token, {
							expires: expires,
						})
						util.cookies.setSupplier('uuid', data.user_info.id, {
							expires: expires,
						})
						util.cookies.setSupplier('expires_time', expires, {
							expires: expires,
						})
						util.cookies.setSupplier('pageTitle', row.supplier_name);
						util.makeMenu(`/${data.prefix}`, data.menus)
						let storage = window.localStorage
						storage.setItem('menuListSupplier', JSON.stringify(data.menus))
						storage.setItem(
							'uniqueAuthSupplier',
							JSON.stringify(data.unique_auth)
						)
						let userInfoSupplier = {
							account: data.user_info.account,
							head_pic: data.user_info.avatar,
							logo: data.logo,
							logoSmall: data.logo_square,
							version: data.version,
						}
						storage.setItem('userInfoSupplier', JSON.stringify(userInfoSupplier))
						this.BaseURL = Setting.apiBaseURL.replace(/adminapi/, `${row.prefix}/home/`);
						window.open(this.BaseURL)
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},

			// 删除
			del(row, tit, num) {
				let data = {
					ids: row.id,
				}
				let delfromData = {
					title: tit,
					num: 0,
					url: `/supplier/deleteCustomerInformation`,
					method: 'DELETE',
					ids: data,
				}
				this.$modalSure(delfromData)
					.then((res) => {
						this.$Message.success(res.msg)
						this.tabList.splice(num, 1);
						if (!this.tabList.length) {
							this.page.pageNum =
								this.page.pageNum == 1 ? 1 : this.page.pageNum - 1;
						}
						this.getSupplier()
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},
		},
	}
</script>
<style scoped lang="less">
	.input-add {
		width: 250px;
		margin-right: 14px
	}

	.btn {
		margin: 0 0 10px 0px;
	}

	.del {
		margin-left: 10px;
	}

	// .card {
	//   margin-top: 15px;
	// }
	.ivu-form-inline {
		padding-top: 20px;
	}

	.follow_content {
		white-space: pre-line;
		border-radius: 6px;
		background: #ffffff;
		padding: 16px 20px;
		border: 1px solid #e5e5e5;
		box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
		font-size: 14px;
		color: #333;
		line-height: 1.7;
		max-height: 300px;
		overflow-y: auto;
	}

	.floatRight {
		float: right
	}

	/* 添加样式 */
	.follow-item {
		margin-bottom: 16px;
		padding: 12px;
		border: 1px solid #dcdee2;
		border-radius: 4px;
		position: relative;
	}

	.follow-header {
		margin-bottom: 8px;
		color: #808695;
		font-size: 12px;
	}

	.follow-content {
		width: 100% !important;
	}

	.follow-remove-btn {
		position: absolute;
		top: 10px;
		right: 10px;
	}

	.add-follow-btn {
		margin-top: 8px;
	}
</style>